package cn.funeralobjects.upms.repository;

import cn.funeralobjects.upms.entity.EUserRole;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.Collection;
import java.util.List;

/**
 * 用户角色数据接口
 *
 * @author FuneralObjects
 * Create date: 2019/9/10 2:24 AM
 */
public interface UserRoleRepository extends JpaRepository<EUserRole, EUserRole> {
    /**
     * 通过角色id来过滤符合条件的用户id
     *
     * @param roleId  角色id
     * @param userIds 用户id集合
     * @return 过滤出来的用户id
     */
    @Query("SELECT userId FROM EUserRole WHERE roleId =:roleId AND userId in :userIds")
    List<Integer> filterUserIdByRoleId(Integer roleId, Collection<Integer> userIds);

    /**
     * 通过用户id来过滤符合条件的角色id
     *
     * @param userId  用户Id
     * @param roleIds 角色id集合
     * @return 符合条件的角色id集合
     */
    @Query("SELECT roleId FROM EUserRole WHERE userId =:userId AND roleId in :roleIds")
    List<Integer> filterRoleIdByUserId(Integer userId, Collection<Integer> roleIds);

    List<EUserRole> findAllByRoleId(Integer roleId);

    List<EUserRole> findAllByUserId(Integer userId);


    /**
     * 通过角色id删除关联
     *
     * @param roleId 角色id
     */
    @Modifying
    @Query("DELETE FROM EUserRole WHERE roleId = :roleId")
    void deleteAllByRoleId(Integer roleId);

    /**
     * 通过用户id删除关联
     *
     * @param userId 用户id
     */
    @Modifying
    @Query("DELETE FROM EUserRole WHERE userId = :userId")
    void deleteAllByUserId(Integer userId);
}
